package com.atjava.nebula.web.action;

import java.io.Serializable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atjava.nebula.core.exception.baseExp.BusinessException;
import com.atjava.nebula.core.exception.baseExp.SystemException;
import com.atjava.nebula.core.model.BaseModel;
import com.atjava.nebula.core.model.TreeModel;
import com.atjava.nebula.core.service.GenericService;
import com.atjava.nebula.core.util.entity.EntitySupport;
import com.atjava.nebula.core.util.tree.TreeUtils;
import com.atjava.nebula.web.view.XmlViewManager;

/**数据删除的Action
 * @author kyo
 */

@Controller
@RequestMapping("/base/delete")
public class DelAction<T extends BaseModel,ID extends Serializable> extends BaseViewAction  {
	
	//json response
	@SuppressWarnings("unchecked")
	@RequestMapping("/do/**")
	@ResponseBody
	public boolean delete(HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(REQ_PARAM_QUERYPK) String [] pkid,
			@RequestParam(REQ_PARAM_CATALOG) String catalog,
			@RequestParam(REQ_PARAM_ENTITY) String entity,
			ModelMap modelMap) throws SystemException, BusinessException {
		
		GenericService<T,ID> baseService = (GenericService<T,ID>) getService(catalog,entity);
		Class<?> entityClass = XmlViewManager.getEntityClass(catalog, entity);
		
		//begin transcation
		if(TreeUtils.isTreeModel(entityClass)){
			GenericService<TreeModel,?> treeService = (GenericService<TreeModel,?>)baseService;
			List<TreeModel> treeList = treeService.getAll();
			for (int i = 0; i < pkid.length; i++) {
				
				TreeModel idEntity = (TreeModel) EntitySupport.getPkToEntity(entityClass,pkid[i]);
				treeService.remove(idEntity);
				
				TreeModel selectedNode = TreeUtils.getTreeObject(treeList, idEntity);
				//TreeUtils.getChildNodesIdList(treeIdList, selectedNode);
				
				List<TreeModel> childNodes = selectedNode.getChildNodes();
				if(childNodes != null){
					for (int j = 0; j < selectedNode.getChildNodes().size(); j++) {
						treeService.remove(selectedNode.getChildNodes().get(j));
					}
				}
			}
			
		}else{
			for (int i = 0; i < pkid.length; i++) {
				T idEntity = (T) EntitySupport.getPkToEntity(entityClass,pkid[i]);
				baseService.remove(idEntity);
			}
		}
		
		return true;
		
	}

}
